$(function(){
	var nodeMetaData = {};			//	store the fetched meta-data for specified monitored group
	var selectedGroup = null;	//	store the ID of selected group
	var selectedNode = null;	//	store the ID of selected node
	
	initPage();
	self.setInterval(periodicFetcher, 1000);
	
	function initPage() {
		$("#groupdiv").append("<center id='grouptitle'><h3>Monitored Groups</h3></center>");
		$("#nodesdiv").append("<center id='nodestitle'><h3>Monitored Nodes</h3></center>");
	}

	/**
	 * Periodically fetch the meta-data from server side.
	 */
	function periodicFetcher(){
		$.getJSON('./retriever', {method: 'retrieveAllGroups'}, function(groups) {
			$("#groupdiv").html("");
			$("#groupdiv").append("<center id='grouptitle'><h3>Monitored Groups</h3></center>");
			$("#groupdiv").append("<table width='100%' id='grouplist'>");
			for(var group in groups) {
				$("#grouplist").append("<tr><td id='group'>" + '' + groups[group] + "</td></tr>");
			}
			//	add action to each group
			$("#grouplist tr").each(function(){
				var groupID = $(this).children().filter("#group").text();
				$(this).bind('click', function(){
					clickGroup(groupID);
				}).css('cursor', 'pointer');
			});
			$("#groupdiv").append("</table>");
		});
		
		//	get all nodes if group is selected
		if(selectedGroup != null) {
			
			$.getJSON('./retriever', {method: 'retrieveAllNodes', groupname: selectedGroup}, function(data){
				$("#nodesdiv").html("");
				$("#nodesdiv").append("<center id='nodestitle'><h3>Monitored Nodes</h3></center>");
				$("#nodesdiv").append("<table width='100%' id='nodelist'>");
				
				for(nodename in data){
					$("#nodelist").append("<tr><td id='node'>" + data[nodename] + "</td></tr>");
				}
				//	add action to each node
				$("#nodelist tr").each(function(){
					var nodeID = $(this).children().filter("#node").text();
					$(this).bind('click', function(){
						clickNode(nodeID);
					}).css('cursor', 'pointer');
				});
				$("#nodesdiv").append("</table>");
			});
		}
		
		//	get meta data related to node
		if(selectedNode != null) {
			$.getJSON('./retriever', {method: 'retrieveNodeMetaData', groupname:selectedGroup, nodename: selectedNode}, function(data){
				nodeMetaData = data;
			});
		}

	}

	/**
	 * Whenever a group is selected, update the selectedGroup and set selectedNode to null.
	 */
	function clickGroup(id) {
		selectedGroup = id;
		selectedNode = null;
		$("#utilization").children().each(function(){
			$(this).html("");
		});
	}

	/**
	 * Whenever a node is selected, update the graph panel.
	 */
	function clickNode(id){
		selectedNode = id;
		
		if(selectedNode != null) {
			$("#utilization").children().each(function(){
				$(this).html("");
			});
			createCPUVis(selectedNode);
			createMemoryVis(selectedNode);
			createDiskVis(selectedNode);
			createNetworkVis(selectedNode);
		}
	}

	function createCPUVis(id) {
		var cpuMetaData = nodeMetaData['cpu'];
//		if(cpuMetaData == null)
//			return;
		var labels = [];
		var values = [];
		for(var cpu in cpuMetaData) {
			labels.push(cpu);
			values.push(parseFloat(cpuMetaData[cpu]));
		}
		$("#cpusdiv").append("<div id='cpucontainer'></div>");
		$("#cpucontainer").css({width: '98%', height: '98%'}).addClass('center');
		
		new Highcharts.Chart({
			chart : {
				renderTo : 'cpucontainer',
				type : 'column',
				margin : [ 50, 50, 100, 80 ],
				backgroundColor: {
			         linearGradient: [0, 0, 0, 400],
			         stops: [
			            [0, 'rgb(96, 96, 96)'],
			            [1, 'rgb(16, 16, 16)']
			         ]
			    },
				events: {				
					load: function() {
						var series = this.series[0];
						setInterval(function() {
							series.setData(updateCPU(id));
						}, 1000);
					}
				}
			},
			title : {
				text : '' + id + ' CPU Utilization',
				style: {
					color: '#FFF'
				}
			},
			xAxis : {
				categories : labels,
				tickColor: '#999',
				labels : {
					rotation : -45,
					align : 'right',
					style : {
						font : 'normal 13px Verdana, sans-serif',
						color: (Highcharts.theme && Highcharts.theme.textColor) || 'white'
					}
				}
			},
			legend: {
				align: 'right',
				x: -100,
				verticalAlign: 'top',
				y: 20,
				floating: true,
				backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white',
				borderColor: '#CCC',
				borderWidth: 1,
				shadow: false
			},
			yAxis : {
				min : 0.0,
				max : 1.0,
				tickColor: '#C0D0E0',
				title : {
					text : 'Utilization'
				},
				stackLabels: {
					enabled: true,
					verticalAlign: 'top',
					style: {
						fontWeight: 'bold',
						color: (Highcharts.theme && Highcharts.theme.textColor) || 'white'
					}
				},
				style: {
					color: '#FFF'
				}
			},
			legend : {
				enabled : false
			},
			tooltip : {
				formatter : function() {
					return '<b>' + this.x + '</b><br/>'
							+ 'Utilization: '
							+ Highcharts.numberFormat(this.y * 100, 2) + ' %';
				}
			},
			series : [ {
				name : 'Utilization',
				data : values,
				dataLabels : {
					enabled : true,
					rotation : -90,
					color : '#FFFFFF',
					align : 'top',
					x : -3,
					y : 10,
					formatter : function() {
						return Math.round(this.y * 100) / 100;
					},
					style : {
						font : 'normal 13px Verdana, sans-serif'
					}
				}
			} ]
		});
		
	}

	/**
	 * Update the CPU chart.
	 */
	function updateCPU(id) {
		var cpuMetaData = nodeMetaData['cpu'];
		var values = [];
		if(cpuMetaData == null)
			return;
		for(var cpu in cpuMetaData) {
			values.push(parseFloat(cpuMetaData[cpu]));
		}
		return values;
	}

	function createDiskVis(id) {
		var diskMetaData = nodeMetaData['disk'];

	}

	function createMemoryVis(id) {
		var memoryMetaData = nodeMetaData['mem'];
//		if(memoryMetaData == null)
//			return;
		
		var values = [];
		$("#memorydiv").html("");
		$("#memorydiv").append("<div id='memorytablediv'></div>");
		$("#memorytablediv").css({width: '45%', height: '93%'}).addClass('left');
		$("#memorytablediv").append("<table id='memorytable' width='100%' align='center' border='1'>");
		$("#memorytable").append("<tr><td>Property</td><td>Value (KB)</td></tr>");
		for(var elem in memoryMetaData) {
			$("#memorytable").append("<tr><td>" + elem + "</td><td>" + memoryMetaData[elem] + "</td></tr>");
			if(elem != 'MemTotal:')
				values.push([elem, parseInt(memoryMetaData[elem])]);
		}
		$("#memorytablediv").append("</table>");
		
		setInterval(updateMemoryTable, "1000");
		setInterval(updateMemory, "1000");
		
		$("#memorydiv").append("<div id='memorycontainer'></div>");
		$("#memorycontainer").css({width: '45%', height: '93%'}).addClass('right');
		
		new Highcharts.Chart({
			chart: {
				renderTo: 'memorycontainer',
				plotBackgroundColor: null,
				plotBorderWidth: null,
				plotShadow: false,
				events: {				
					load: function() {
						var series = this.series[0];
						setInterval(function() {
							series.setData(updateMemory());
						}, 1000);
					}
				}
			},
			title: {
				text: 'Memory Usage'
			},
			tooltip: {
				formatter: function() {
					return '<b>'+ this.point.name +'</b>: '+ Math.round(this.percentage * 100) / 100 +' %';
				}
			},
			plotOptions: {
				pie: {
					allowPointSelect: true,
					cursor: 'pointer',
					dataLabels: {
						enabled: false
					},
					showInLegend: true
				}
			},
			series: [{
				type: 'pie',
				name: 'Memory',
				data: values
			}]
		});
	}
	
	function updateMemoryTable() {
		$("#memorytable").html("");
		$("#memorytable").append("<tr><td>Property</td><td>Value (KB)</td></tr>");
		var memoryMetaData = nodeMetaData['mem'];
		for(var elem in memoryMetaData) {
			$("#memorytable").append("<tr><td>" + elem + "</td><td>" + memoryMetaData[elem] + "</td></tr>");
		}
	}
	
	function updateMemory() {
		var memoryMetaData = nodeMetaData['mem'];
		var values = [];
		for(var elem in memoryMetaData) {
			if(elem != 'MemTotal:') 
				values.push([elem, parseInt(memoryMetaData[elem])]);
		}
		return values;
	}

	function createNetworkVis(di) {
		
	}
	
});

